const express=require('express');
const u=express.Router();
const pool=require('../pool.js');
u.post('/reg',(req,res,next)=>{
	if(!req.body.uname){
	  res.send({code:401,msg:'用户名不能为空'});
	  return;
	  }else if(!req.body.upwd){
	  res.send({code:402,msg:'密码不能为空'});
	  return;
	  }else if(!req.body.email){
	  res.send({code:403,msg:'邮箱不能为空'});
	  return;
	  }else if(!req.body.phone){
	  res.send({code:404,msg:'手机号不能为空'});
	  return;
	  }else if(!/^1[3-9]\d{9}$/.test(req.body.phone)){
	  res.send({code:405,msg:'手机号格式错误'});
	  return;
	  };
	  pool.query('insert into xz_user set?',[req.body],(err,result)=>{
	       if(err){
		     next(err);
			 return;
		   };
		   res.send({code:200,msg:'注册成功'});
	  });
});
//登录
u.post('/login',(req,res,next)=>{
    var a=req.body;
	if(!a.uname){
	  res.send({code:401,msg:'用户名不能为空'});
	  return;
	}else if(!a.upwd){
	  res.send({code:402,msg:'密码不能为空'});
	  return;
	};
	pool.query('select * from xz_user where uname=? && upwd=?',[a.uname,a.upwd],(err,result)=>{
		console.log(result);
	if(err){
	   next(err);
	   return;
	   };
	   
	   if(result.length!==0){
       res.send({code:200,msg:'登录成功'})
	   }else{
	   res.send({code:201,msg:'登录失败'}) 
	   };
	});
});

//删除
u.delete('/:uid',(req,res,next)=>{
    //console.log(111);
	var obj = req.params;
	console.log(obj);
	pool.query('delete from xz_user where uid=?',[obj.uid],(err,result)=>{
	     if(err){
		   next(err);
		   return;
		 };
		 if(result.affectedRows===0){
		   res.send({code:201,msg:'删除失败'})  
		 }else{
		   res.send({code:201,msg:'删除成功'}) 
		 }
	});

});
//修改
u.put('/',(req,res,next)=>{
	  var i=400;
	  for(var k in req.body){
	     //k代表属性名  []属性值
		 //console.log(k,req.body[k]
		 //如果属性值为空，提示属性名这项不能为空		 
		 i++;
		 if(!req.body[k]){
		   res.send({code:i,msg:k+'不能为空'});
		   return;
		 }
	  };
      pool.query('update xz_user set ? where uid=?',[req.body,req.body.uid],(err,result)=>{
	     if(err){
		    next(err);
			return;
		 };
		 if(result.changedRows===0){
		  res.send({code:201,msg:'修改失败'})   
		 }else{
		  res.send({code:201,msg:'修改成功'})  
		 }
	  });
});

module.exports=u;
























